package com.inspur.xiaoju.service.impl;

import com.inspur.xiaoju.dto.CreateWorkspaceDto;
import com.inspur.xiaoju.exception.BusinessException;
import com.inspur.xiaoju.model.Workspace;
import com.inspur.xiaoju.repository.WorkspaceRepository;
import com.inspur.xiaoju.service.WorkspaceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class WorkspaceServiceImpl implements WorkspaceService {

    @Autowired
    private WorkspaceRepository workspaceRepository;
    
    @Override
    public Workspace create(CreateWorkspaceDto createDto, String creatorId, String creator) {
        Workspace workspace = new Workspace();
        workspace.setName(createDto.getName());
        workspace.setDescription(createDto.getDescription());
        workspace.setCreatorId(creatorId);
        workspace.setCreator(creator);
        
        Date now = new Date();
        workspace.setCreateDate(now);
        workspace.setUpdateDate(now);
        
        return workspaceRepository.save(workspace);
    }
    
    @Override
    public Workspace findById(String id) {
        return workspaceRepository.findById(id)
                .orElseThrow(() -> new BusinessException(404, "工作区不存在"));
    }
    
    @Override
    public List<Workspace> findByCreatorId(String creatorId) {
        return workspaceRepository.findByCreatorId(creatorId);
    }
    
    @Override
    public Workspace update(String id, Map<String, Object> updates) {
        Workspace workspace = findById(id);
        
        if (updates.containsKey("name")) {
            workspace.setName((String) updates.get("name"));
        }
        
        if (updates.containsKey("description")) {
            workspace.setDescription((String) updates.get("description"));
        }
        
        workspace.setUpdateDate(new Date());
        
        return workspaceRepository.save(workspace);
    }
    
    @Override
    public void delete(String id) {
        workspaceRepository.deleteById(id);
    }
}